<template>
	<Content :title="type == '1' ? '生产加料' : '生产退料'" rightIcon="scan" @rightClick="scanCode">
		<view class="device-details">
			<view class="content">
				<view class="top-box">
					<view class="info-box" style="padding: 10px">
						<u-input class="box-input" prefixIcon="search" prefixIconStyle="font-size: 22px;color: #909399"
							border="none" label v-model="search.materialCode" placeholder="请输入物料编号"
							@change="getList(true)" clearable></u-input>
					</view>

					<view class="info-box" style="padding-bottom: 5px">
						<view class="title">
							<view class="label"> 物料选择 </view>
							<view class="value" style="color: #67aee7">
								<u-checkbox-group shape="circle" v-model="radio" @change="checkboxChange">
									<u-checkbox :name="1" label="全选"></u-checkbox>
								</u-checkbox-group>
							</view>
						</view>
					</view>
				</view>
				<view class="main-box">
					<view class="info-box">
						<u-form labelPosition="left" :model="model" labelWidth="80" labelAlign="left" :rules="rules"
							ref="uForm">
							<view class="input-box">
								<u-form-item label="班次时间:" required prop="shiftTime">
									<MyDate @change="getShiftList" v-model="model.shiftTime" placeholder="请选择"></MyDate>
								</u-form-item>
							</view>
							<view class="input-box">
								<u-form-item label="班次:" required prop="shift">
									<uni-data-select v-model="model.shift" :localdata="shiftList" :clear="false"
										@change="getShiftTime" placeholder="请选择"></uni-data-select>
								</u-form-item>
							</view>
						</u-form>
					</view>

					<List ref="orderList" :scrollNoData="scrollNoData" :data="data" :option="option"
						:wareHouses="wareHouses" :type="type" @itemClick="itemClick" @onRefresh="onRefresh"
						@scrollBottom="scrollBottom"></List>
				</view>

				<view class="btn-v">
					<view class="but-box">
						<u-button class="btn" type="primary" @click="replaceMold" :loading="loading" :disabled="loading" text="确定"></u-button>
					</view>
				</view>
			</view>
		</view>
		<MyModal
		  v-model="show"
		  :title="modalTitle"
		  :content="content"
		  @confirm="confirm"
		  ref="uModal"
		  :showCancelButton="true"
		></MyModal>
	</Content>
</template>

<script>
	import MyModal from "@/components/myModal.vue";
	import Content from "@/components/content/index";
	import fetch from "@/utils/fetch";
	import {
		getUserInfo
	} from "@/store/user";
	import List from "./list";
	import MyDate from "@/components/myDate.vue";
	import {
		initScan,
		startScan,
		stopScan
	} from "@/utils/scan";
	export default {
		props: {
			type: {
				type: String,
				default: "1",
			},
			option: {
				type: Object,
				default: () => {},
			},
		},
		components: {
			Content,
			MyModal,
			List,
			MyDate,
		},
		data() {
			return {
				model: {
					shiftTime: "",
					shiftId: "",
					shift: "",
				},
				data: [],
				content:'',
				rules: {
					materialBatch: {
						required: true,
						message: "请填写",
						trigger: ["blur", "change"],
					},
					shift: {
						required: true,
						message: "请填写",
						trigger: ["blur", "change"],
					},
					shiftTime: {
						required: true,
						message: "请填写",
						trigger: ["blur", "change"],
					},
					weight: {
						type: "number",
						required: true,
						message: "请填写",
						trigger: ["blur", "change"],
					},
					unit: {
						required: true,
						message: "请填写",
						trigger: ["blur", "change"],
					},
					warehouse: {
						required: true,
						message: "请填写",
						trigger: ["blur", "change"],
					},
				},
				search: {
					workCode: "",
					materialCode: "",
					productMaterialCode: "",
					planProduceQuantity: "",
					pageNum: 1,
					pageSize: 10,
				},
				shiftList: [],
				wareHouses: [],
				navIndex: 0,
				id: "",
				show: false,
				modalTitle: "",
				radioGroup: "",
				materialCode: "",
				scroll: false,
				loading: false,
				scrollNoData: false,
				arr: [],
				radio: [],
				postData:{},
			};
		},
		computed: {},
		async mounted() {
			console.log("this.option", this.option);
			this.model.shiftTime = this.$dayjs(new Date()).format("YYYY-MM-DD");
			this.search.workCode = this.option.workCode;
			// this.search.productMaterialCode = this.option.materialCode;
			// this.search.planProduceQuantity = this.option.planProduceQuantity;
			await this.getWareHouseList();
			await this.getShiftList();
			this.getList();
			
			// #ifdef APP-PLUS
			console.log('init初始化')
			initScan(this.scanSuccess);
			startScan();
			// #endif
			
		},
		async destroyed() {
			// #ifdef APP-PLUS
			console.log('结束了')
			stopScan();
			// #endif
		},
		methods: {
			async scanSuccess(code) {
				console.log('红外线扫码的结果', code);
				const res = {
					result: code,
				};
				this.$refs.orderList.afterScan(res);
			},
			//班次列表
			getShiftList() {
				const that = this;
				return fetch("get", "/dms/mobile/getShiftList", {
					deviceNo: this.option.deviceCode,
					shiftDate: that.model.shiftTime,
				}).then((res) => {
					const now = that.$dayjs().format("YYYY-MM-DD") + " ";
					const newDate = that.$dayjs().format("YYYY-MM-DD HH:mm:ss");
					const now1 = that.$dayjs().add(1, "day").format("YYYY-MM-DD") + " ";
					that.shiftList = res.data.map((item) => {
						const startTime = now + item.shiftStartTime;
						let endTime = now + item.shiftEndTime;
						if (endTime < startTime) {
							endTime = now1 + item.shiftEndTime;
						}
						console.log("startTime, endTime", startTime, endTime, newDate);
						if (newDate > startTime && newDate < endTime) {
							that.model.shift = item.shift;
							that.model.shiftId = item.id;
						}
						return {
							...item,
							value: item.shift,
							text: item.shift,
						};
					});

					if (!that.model.shift) {
						that.model.shift = that.shiftList[0].shift;
						that.model.shiftId = that.shiftList[0].id;
					}

					console.log("that.shiftList", that.shiftList);
				});
			},
			getWareHouseList() {
				fetch("get", "/dms/mobileEnd/getUseWarehouse", {
					deviceNo: this.option.deviceCode,
				}).then((res) => {
					this.wareHouses = [res.data].map((item) => ({
						...item,
						value: item.backupName,
						text: item.backupName,
					}));
				});
			},
			getShiftTime(val, data) {
				this.model.shiftId = data.id;
				console.log("getShiftTime----------", this.model.shiftId);
			},
			checkboxChange(val) {
				if (val && val[0]) {
					// this.$refs.list.
					this.$refs.orderList.setAllRadioGroup();
				} else {
					this.$refs.orderList.setCloseRadioGroup();
				}
			},
			scanCode() {
				this.$refs.orderList.scanCode();
			},
			onRefresh() {
				this.getList(true);
			},
			ok() {},
			itemClick(i, data) {
				this.arr = data;
			},
			replaceMold() {
				const that = this;
				this.$refs.uForm.validate().then((valid) => {
					if (valid) {
						if (that.arr.length === 0) {
							uni.$emit("openToast", {
								type: "error",
								icon: "error",
								title: "请选中一条数据!",
							});
							return;
						}
						const model = that.model;
						that.$refs.orderList.getValidate().then((valid) => {
							if (valid) {
								const userInfo = getUserInfo();
								const data = that.$refs.orderList.getData().map((item) => {
									return {
										feedingStatus: that.type == "1" ? "加料" : "退料",
										materialBatch: item.materialBatch,
										materialCode: item.materialCode,
										operator: userInfo.realname,
										remarks: item.remarks,
										unit: item.unit,
										warehouse: item.warehouse,
										weight:item.weight,
										workCode: that.option.workCode,
										shiftTime: model.shiftTime,
										shift: model.shift,
										shiftId: model.shiftId,
										warehouseId: item.warehouseId,
										tagSerialNumber: item.tagSerialNumber,
									};
								});
								this.postData=data;
								this.content='确认提交吗？';
								const params=data.map(item=>{
									return{
										workCode: that.option.workCode,
										materialCode: item.materialCode,
										batchNumber: item.materialBatch || ' ',
									}
								})
								this.loading=true;
								fetch('post', '/dms/materialOperation/queryMaterialLimitation', params).then((res) => {
									this.loading=false;
								   if(res.data.includes(1)){
									   uni.$emit("openToast", {
									   	type: "error",
									   	icon: "error",
									   	title: "禁止挪用投料!",
									   });
									  return;
								   }else if(res.data.includes(2)){
									   this.content='该投料订单与当前生产订单无关'
								   }
								   that.show=true;
								});
							}
						});
					}
				});
			},
			confirm(){
				const that=this;
				fetch(
					"post",
					"/dms/mobileEnd/" +
					(that.type == "1" ?
						"addMaterialOperation" :
						"updateMaterialOperation"),
					that.postData
				).then((res) => {
					that.show=false;
					uni.$emit("openToast", {
						type: "success",
						title: res.msg,
						complete() {
							that.getList(true);
						},
					});
				});
			},
			scrollBottom(next) {
				const that = this;
				if (!that.scrollNoData) {
					that.search.pageNum = that.search.pageNum + 1;
					that.scroll = true;
					that.getList().then(() => {
						next(that.scrollNoData);
					});
					return;
				}
				next();
			},
			getList(arg) {
				const that = this;
				that.$loading.open();
				if (arg) {
					that.search.pageNum = 1;
					that.scroll = false;
					that.scrollNoData = false;
					that.data = [];
				}
				let obj = {};
				for (const key in that.search) {
					if (Object.hasOwnProperty.call(that.search, key)) {
						const element = that.search[key];
						if (element) obj[key] = element;
					}
				}
				obj.shiftId = that.model.shiftId;
				return fetch("get", "/dms/mobileEnd/getMaterialAddList", obj).then(
					({
						data
					}) => {
						data = data?.records || [];
						data = data.map((item) => {
							return {
								...item,
								warehouse: that.wareHouses[0].backupName,
								warehouseId: that.wareHouses[0].id,
							};
						});
						if (that.scroll) {
							if (data.length === 0) {
								that.scrollNoData = true;
							} else {
								that.data.push(...data);
							}
						} else {
							that.data = data;
						}

						that.$loading.close();
					}
				);
			},
		},
	};
</script>

<style scoped lang="scss">
	.device-details {
		height: 100%;
		overflow: auto;
		padding-bottom: 160rpx;

		.content {
			height: 100%;
			display: flex;
			flex-direction: column;
		}

		.main-box {
			display: flex;
			flex-direction: column;
			flex: 1;
			overflow: auto;

			.top-box {
				height: 118px;
			}
		}

		.title {
			font-size: 32rpx;
			margin-bottom: 20rpx;
			padding: 0 40rpx 0 40rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.txt {
				flex: 1;
			}

			.tag-box {
				display: flex;
				align-items: center;
			}
		}

		.content-top {
			padding: 40rpx;

			.state {
				color: #f17a0a;
				margin-bottom: 20rpx;
			}
		}

		.text-box {
			display: flex;
			margin-bottom: 20rpx;

			.label {
				color: #666;
			}
		}

		.search-box {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 60rpx;

			.label {
				margin: 0 20rpx;
			}
		}

		.number-davities-box {
			text-align: center;

			.header {
				margin-bottom: 20rpx;
			}

			.item-box {
				display: flex;
				justify-content: space-between;
				margin-bottom: 20rpx;
			}
		}

		.btn-box {
			display: flex;

			.btn-box-item {
				padding: 20rpx;
				flex: 1;
				text-align: center;
				border-top: 1px solid #e0e0e0;
				border-right: 1px solid #e0e0e0;
				color: #67aee7;
			}
		}
	}
</style>